<?php

function createsessions($username,$password,$email)
{
    $_SESSION["gdusername"] = $username;
    $_SESSION["gdpassword"] = $password; // md5($password);
    $_SESSION["gdemail"] = $email;
}

function clearsessionscookies()
{
    unset($_SESSION['gdusername']);
    unset($_SESSION['gdpassword']);
    
    session_unset();    
    session_destroy(); 

    setcookie ("gdusername", "",time()-60*60*24*100, "/");
    setcookie ("gdpassword", "",time()-60*60*24*100, "/");
}

function confirmUser($username,$password)
{
    // $md5pass = md5($password); // Not needed any more as pointed by ted_chou12
    /* Validate from the database but as for now just demo username and password */

    $dbconn = pg_connect("host=geo.bluecityexchange.org dbname=crwaorg_bce user=crwaorg password=charles7");
    $result = pg_query("select count(*) from bce_users where id = '$username' and pw = md5('$password')");
    $hits = 0;
    while ($line = pg_fetch_array($result)) {
      $hits = $line[0];
    }
    pg_close($dbconn);

    if ($hits == 1) {
      setcookie("failedLogin");
      return true;
    }
    else {
      setcookie("failedLogin",'login');
      return false;
    }
}

function confirmUserRegistration($username,$password,$email)
{
    // $md5pass = md5($password); // Not needed any more as pointed by ted_chou12
    /* Validate from the database but as for now just demo username and password */

    $dbconn = pg_connect("host=geo.bluecityexchange.org dbname=crwaorg_bce user=crwaorg password=charles7");
    $err    = '';
    $result = pg_query("insert into bce_users(id,pw,email) values ('$username',md5('$password'),'$email')");

    setcookie("failedLogin");
    if (!$result) {
      setcookie("failedRegister",'reigster');
      return false;
    }
    else {
      setcookie("failedRegister");
      return true;
    }
}

function checkLoggedin()
{
    if(isset($_SESSION['gdusername']) AND isset($_SESSION['gdpassword']))
        return true;
    elseif(isset($_COOKIE['gdusername']) && isset($_COOKIE['gdpassword']))
    {
        if(confirmUser($_COOKIE['gdusername'],$_COOKIE['gdpassword']))
        {
            createsessions($_COOKIE['gdusername'],$_COOKIE['gdpassword']);
            return true;
        }
        else
        {
            if ($_COOKIE['failedLogin']) {
              clearsessionscookies();
              setcookie("failedLogin",true);
            }
            else {
              clearsessionscookies();
            }
            return false;
        }
    }
    else
        return false;
}
?> 
